package csel.model;

import java.io.*;

import csel.model.entity.*;

/**
 * Simply creates games.
 * @author david
 */
public class GameFactory
{
	/**
	 * Create a basic game with the specified occupation.
	 * @param occupation
	 * @throws IOException
	 */
	public static void makeNewGame(Occupation occupation, String name, Model model)
	{
		GameGlobals globals;
		Map map;
		PlayerCharacter player;
		GameData data;
		
		if (model == null)
			throw new IllegalArgumentException("Must specify a model.");
		
		globals = new GameGlobals();
		
		try
		{
			map = loadMap("maps/default.map", globals);
		}
		catch (FileNotFoundException ex)
		{
			throw new GameLoadException("Could not locate map file.", ex);
		}
		catch (IOException ex)
		{
			throw new GameLoadException(String.format("Map file corrupt. (%s)", ex.toString()), ex);
		}
		
		player = new PlayerCharacter(occupation, name);
		player.init();
		player.move(map.getStartingTile());   // move will just set location (and will set entity in tile)

		map.attach(globals);
		
		data = GameData.makeGameData(globals, player, map);
		
		globals.getChronoTrigger().start();
		
		/* update the model... this should be last! */
		model.setGameData(data);
	}
	
	private static Map loadMap(String filepath, GameGlobals globals)
		throws FileNotFoundException, IOException
	{
		FileInputStream fileIn;
		ObjectInputStream serializer;
		Map map;
	
		fileIn = new FileInputStream(filepath);
		serializer = new ObjectInputStream(fileIn);
	
		try
		{
			map = (Map)serializer.readObject();
		} catch (ClassNotFoundException ex)
		{
			throw new IOException("Invalid save file data.", ex);
		}
	
		serializer.close();
		fileIn.close();
		
		return map;

	}
}
